import React, { PureComponent, Fragment } from 'react';

import {
  CloseCircleOutlined,
  DownOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
} from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import {
  Row,
  Col,
  Card,
  Select,
  Button,
  Input,
  Dropdown,
  DatePicker,
  Menu,
  message,
  Alert,
  Badge,
  Tooltip,
  Divider,
  Modal,
  Spin,
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import MenuItem from 'antd/lib/menu/MenuItem';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import downloadFile, { formatNumber } from '@/utils/utils';
import Authorized from '@/utils/Authorized';
import TextOverFlow from '../../components/TextOverFlow';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { Option } = Select;
const { MonthPicker } = DatePicker;
let uploadFiles = null;
@connect(({ pay, loading }) => ({
  pay,
  data: pay.data,
  expandForm: pay.expandForm,
  loading: loading.models.pay,
  formFieldsValue: pay.formFieldsValue,
  valuesArr: pay.valuesArr,
}))
@Form.create()
class Pay extends PureComponent {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
    statusMap: ['', 'default', 'processing', 'warning', 'success', 'success'],
    priceSum: 0,
    exportLoding: false,
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount() {
    this.getBillState();
    this.getReceive();
    this.getInitialList();
  }

  componentWillUnmount() {
    window.clearInterval(uploadFiles);
  }

  // 获得账单状态
  getBillState = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'pay/fetchBillState',
      payload: ['NSBILL_PAY_STATE'],
    });
  };

  // 获得接单方
  getReceive = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'pay/fetchReceive',
      payload: {
        name: null,
      },
    });
  };

  getInitialList = () => {
    const {
      data: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      if (location.queryParam && location.queryParam.suppId) {
        location.queryParam.recvSuppId = location.queryParam.suppId;
        delete location.queryParam.suppId;
      }
      dispatch({
        type: 'pay/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'pay/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    currentPage = 1,
    pageSize = 10,
    isClear = true,
  ) => {
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
        priceSum: 0,
      });
    }

    const { dispatch } = this.props;
    const pageArg = {
      currentPage,
      pageSize,
    };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'pay/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'pay/fetchList',
      payload: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'billNo' && tempFieldsValue[key]) {
        tempFieldsValue[key] = tempFieldsValue[key].trim();
      }
      formFieldsValue[key] = tempFieldsValue[key];
    });
    if (formFieldsValue.billYm) {
      formFieldsValue.billYm = moment(formFieldsValue.billYm).format('YYYYMM');
    }
    return formFieldsValue;
  };

  toggleForm = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'pay/updateModelData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  renderForm = () => {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  };

  // 重置上方搜索表单
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'pay/updateModelData',
      payload: {
        formFieldsValue: {},
      },
    });
    form.resetFields();
    form.setFieldsValue({ billYm: null });
  };

  // 单个下载
  exportSingle = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    if (!selectedRowKeys.length) {
      message.warning('请至少选择一条账单数据');
    } else {
      // downloadFile({ billIdList: selectedRowKeys }, '/nsApi/nsBillPay/downSingleBillDet', 'POST');
      const params = {
        billIdList: selectedRowKeys,
      };
      this.setState({
        exportLoding: true,
      });
      dispatch({
        type: 'pay/singleExport',
        payload: params,
      }).then(res => {
        if (res.success) {
          uploadFiles = setInterval(() => {
            dispatch({
              type: 'pay/uploadFile',
              payload: { billKey: res.data, downType: 2 },
            }).then(resFile => {
              if (resFile.success) {
                if (
                  resFile.success &&
                  resFile.data &&
                  resFile.data.fileId &&
                  resFile.data.fileName
                ) {
                  downloadFile({ fileId: resFile.data.fileId, fileName: resFile.data.fileName });
                  window.clearInterval(uploadFiles);
                  this.setState({
                    exportLoding: false,
                  });
                }
              } else {
                message.warning(resFile.message || '下载失败');
                window.clearInterval(uploadFiles);
                this.setState({
                  exportLoding: false,
                });
              }
            });
          }, 2000);
        } else {
          this.setState({
            exportLoding: false,
          });
          window.clearInterval(uploadFiles);
          message.warning(res.message || '下载失败');
        }
      });
    }
  };

  // 合并下载
  exportMarge = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    if (!selectedRowKeys.length || selectedRowKeys.length < 2) {
      message.warning('请至少选择两条账单数据');
    } else {
      // downloadFile({ billIdList: selectedRowKeys }, '/nsApi/nsBillPay/downMergeBillDet', 'POST');
      const params = {
        billIdList: selectedRowKeys,
      };
      this.setState({
        exportLoding: true,
      });
      dispatch({
        type: 'pay/mergeExport',
        payload: params,
      }).then(res => {
        if (res.success) {
          uploadFiles = setInterval(() => {
            dispatch({
              type: 'pay/uploadFile',
              payload: { billKey: res.data, downType: 3 },
            }).then(resFile => {
              if (resFile.success) {
                if (
                  resFile.success &&
                  resFile.data &&
                  resFile.data.fileId &&
                  resFile.data.fileName
                ) {
                  downloadFile({ fileId: resFile.data.fileId, fileName: resFile.data.fileName });
                  window.clearInterval(uploadFiles);
                  this.setState({
                    exportLoding: false,
                  });
                }
              } else {
                message.warning(resFile.message || '下载失败');
                window.clearInterval(uploadFiles);
                this.setState({
                  exportLoding: false,
                });
              }
            });
          }, 2000);
        } else {
          this.setState({
            exportLoding: false,
          });
          window.clearInterval(uploadFiles);
          message.warning(res.message || '下载失败');
        }
      });
    }
  };

  // 标记以支付
  markPay = () => {
    const {
      dispatch,
      data: { pagination },
      formFieldsValue,
    } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择标记已支付的数据');
      return;
    }
    let stateFlag;
    const billNoList = [];
    selectedRows.forEach(item => {
      if (+item.billState !== 2) {
        stateFlag = true;
        billNoList.push(item.billNo);
      }
    });
    if (stateFlag) {
      message.warning(
        `账单编号${billNoList.length > 1 ? '分别' : ''}为“${billNoList.join(
          '、'
        )}”的账单不允许标记已支付，只能针对状态为“待发财务”的账单操作标记已支付!`
      );
      return;
    }
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: `已选择${selectedRowKeys.length}条数据，是否确认全部标记已支付`,
      content: '请线下和财务核实每笔账单已支付，标记后不可取消标记',
      cancelText: '取消',
      okText: '确认',
      onOk: () => {
        dispatch({
          type: 'pay/markPay',
          payload: {
            billIdList: selectedRowKeys,
          },
        }).then(res => {
          if (res.success) {
            if (res.data) {
              if (res.data.taskCount === res.data.successCount) {
                message.success('标记成功');
                this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
              } else if (res.data.taskCount === res.data.errorCount) {
                Modal.error({
                  icon: <CloseCircleOutlined />,
                  title: '标记失败',
                  content: '所选数据非待发财务状态，不可标记已收费',
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
                  },
                });
              } else {
                Modal.warning({
                  icon: <ExclamationCircleOutlined />,
                  title: `标记成功`,
                  content: `已选${res.data.taskCount}条数据中，${
                    res.data.successCount
                  }条已标记成功，${res.data.errorCount}条数据状态非支付，不可标记`,
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
                  },
                });
              }
            }
          } else {
            message.warning(res.message);
          }
        });
      },
    });
  };

  // 展开之后的表单项
  renderAdvancedForm = () => {
    const {
      form: { getFieldDecorator },
      pay: { billStateList, receiveList },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="接单方" {...this.tableSearchLayout}>
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId,
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {receiveList.map(item => (
                    <Option key={item.suppId} title={item.name}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账单年月" {...this.tableSearchLayout}>
              {getFieldDecorator('billYm', {
                initialValue: formFieldsValue.billYm,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账单状态" {...this.tableSearchLayout}>
              {getFieldDecorator('billState', {
                initialValue: formFieldsValue.billState,
              })(
                <Select placeholder="请选择" style={{ width: '100%' }} allowClear>
                  {billStateList.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="账单编号" {...this.tableSearchLayout}>
              {getFieldDecorator('billNo', {
                initialValue: formFieldsValue.billNo,
              })(<Input placeholder="请输入证件号" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={{ span: 8, offset: 8 }} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.searchBtnList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 展开之前的表单项
  renderSimpleForm = () => {
    const {
      form: { getFieldDecorator },
      pay: { receiveList },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="接单方" {...this.tableSearchLayout}>
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId,
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {receiveList.map(item => (
                    <Option key={item.suppId} title={item.name}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账单年月" {...this.tableSearchLayout}>
              {getFieldDecorator('billYm', {
                initialValue: formFieldsValue.billYm,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div>
                <Button type="primary" htmlType="submit" onClick={() => this.searchBtnList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开
                  <DownOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 选中一行时
  handleSelectRows = (selectedRows, selectedKeys) => {
    const priceSum = selectedRows.reduce(
      (total, currentValue) => total + currentValue.billAmo || 0,
      0
    );
    this.setState({
      priceSum,
      selectedRows,
      selectedRowKeys: selectedKeys,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'pay/selectRow',
      payload: {
        selectedRows,
        selectedKeys,
      },
    });
  };

  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize, false);
  };

  // 确认
  confirmStatus = billId => {
    const { dispatch, formFieldsValue } = this.props;
    dispatch({
      type: 'pay/confirmStatus',
      payload: {
        billId,
      },
      callback: res => {
        if (res.success) {
          message.success('操作成功');
          this.searchList(this.processFormData(formFieldsValue));
        }
      },
    });
  };

  // 拒绝
  refuseStatus = billId => {
    const { dispatch, formFieldsValue } = this.props;
    dispatch({
      type: 'pay/refuseStatus',
      payload: {
        billId,
      },
      callback: res => {
        if (res.success) {
          message.success('操作成功');
          this.searchList(this.processFormData(formFieldsValue));
        }
      },
    });
  };

  render() {
    const {
      loading,
      pay: { data },
    } = this.props;
    const { selectedRowKeys, statusMap, priceSum, selectedRows, exportLoding } = this.state;
    const billDownload = (
      <Menu>
        <MenuItem>
          <a onClick={this.exportSingle}>单个下载</a>
        </MenuItem>
        <MenuItem>
          <a onClick={this.exportMarge}>合并下载</a>
        </MenuItem>
      </Menu>
    );
    const columnsDeal = [
      {
        title: '账单年月',
        dataIndex: 'billYm',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '接单方',
        dataIndex: 'recvSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单金额',
        dataIndex: 'billAmo',
        width: 130,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        // render: billAmo => (billAmo ? billAmo.toFixed(2) : null),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  涉及人数：
                  {record.involvePersonNum}
                </p>
                <p>
                  代收社保：
                  {record.agtsrvIns ? formatNumber(record.agtsrvIns) : null}
                </p>
                <p>
                  代收公积金：
                  {record.agtsrvAccu ? formatNumber(record.agtsrvAccu) : null}
                </p>
                <p>
                  代收工资：
                  {record.agtsrvWage ? formatNumber(record.agtsrvWage) : null}
                </p>
                <p>
                  服务费：
                  {record.othCost ? formatNumber(record.othCost) : null}
                </p>
              </div>
            }
          >
            {/* <span>{text === 0 ? 0 : (text && text) || '--'}</span> */}

            {text ? (
              <span>
                {formatNumber(text)}
                <EllipsisOutlined style={{ fontSize: 14, color: '#08c' }} />
              </span>
            ) : (
              <span> {text === 0 ? 0 : '--'}</span>
            )}
          </Tooltip>
        ),
      },
      {
        title: '账单状态',
        dataIndex: 'billState',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => <Badge status={statusMap[text]} text={record.billStateName} />,
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '账单编号',
        dataIndex: 'billNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) =>
          record.billState === 1 ? (
            <Fragment>
              <span
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => router.push(`/paymanage/paybill/detail?billId=${record.billId}`)}
              >
                查看
              </span>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions('ns:nsBillPay:confirmStatus') && (
                      <Menu.Item key="ok" onClick={() => this.confirmStatus(record.billId)}>
                        确认
                      </Menu.Item>
                    )}
                    {checkPermissions('ns:nsBillPay:refuseStatus') && (
                      <Menu.Item key="on" onClick={() => this.refuseStatus(record.billId)}>
                        拒绝
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多 <DownOutlined />
                </a>
              </Dropdown>
              {/* <Authorized authority="ns:nsBillPay:confirmStatus" noMatch={null}>
                <span
                  style={{ color: '#1890FF', cursor: 'pointer' }}
                  onClick={() => this.confirmStatus(record.billId)}
                >
                  确认
                </span>
              </Authorized>
              <Authorized authority="ns:nsBillPay:refuseStatus" noMatch={null}>
                <span
                  style={{ color: '#1890FF', cursor: 'pointer' }}
                  onClick={() => this.refuseStatus(record.billId)}
                >
                  拒绝
                </span>
              </Authorized> */}
            </Fragment>
          ) : (
            <span
              style={{ color: '#1890FF', cursor: 'pointer' }}
              onClick={() => router.push(`/paymanage/paybill/detail?billId=${record.billId}`)}
            >
              查看
            </span>
          ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Spin spinning={exportLoding}>
          <Card className={styles.searchCard} bordered={false}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
          </Card>
          <Card bordered={false} className={styles.tableCard}>
            <Row>
              <Dropdown overlay={billDownload}>
                <Button type="primary">账单下载</Button>
              </Dropdown>
              <Authorized authority="ns:nsBillPay:updateChrgState" noMatch={null}>
                <Button style={{ marginLeft: 8 }} onClick={() => this.markPay()}>
                  标记已支付
                </Button>
              </Authorized>
            </Row>
            <Row className={styles.table}>
              <Alert
                message={
                  <Fragment>
                    已选择 <span style={{ color: '#088FEA' }}> {selectedRows.length} </span>项
                    &nbsp; 总计： &nbsp;
                    <span style={{ fontWeight: 'bold' }}>{priceSum ? priceSum.toFixed(2) : 0}</span>
                    &nbsp;元
                  </Fragment>
                }
                type="info"
                showIcon
                style={{ marginTop: 16, marginBottom: 16, width: '100%' }}
              />
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                selectedRowKeys={selectedRowKeys}
                data={data}
                columns={columnsDeal}
                rowKey="billId"
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </Row>
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Pay;
